<template>
  <div class="novel-content-editor">
    <div class="editor-header">
      <div class="header-left">
        <h3>{{ title }}</h3>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="handleSave" :loading="saving">
          保存
        </el-button>
        <el-button @click="handleReset">重置</el-button>
      </div>
    </div>
    <div class="editor-content">
      <el-input
        v-if="!useRichEditor"
        v-model="content"
        type="textarea"
        :rows="20"
        :placeholder="placeholder"
        resize="none"
      />
      <editor
        v-else
        v-model="content"
        :min-height="500"
        :placeholder="placeholder"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import Editor from '@/components/Editor'

const props = defineProps({
  title: {
    type: String,
    required: true
  },
  modelValue: {
    type: String,
    default: ''
  },
  placeholder: {
    type: String,
    default: '请输入内容...'
  },
  useRichEditor: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue', 'save'])

const content = ref(props.modelValue)
const saving = ref(false)

// 监听内容变化
watch(() => props.modelValue, (newVal) => {
  content.value = newVal
})

// 监听内部内容变化
watch(content, (newVal) => {
  emit('update:modelValue', newVal)
})

// 保存内容
const handleSave = async () => {
  if (!content.value.trim()) {
    ElMessage.warning('请输入内容')
    return
  }

  saving.value = true
  try {
    await emit('save', content.value)
    ElMessage.success('保存成功')
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  } finally {
    saving.value = false
  }
}

// 重置内容
const handleReset = () => {
  content.value = props.modelValue
  ElMessage.info('已重置为上次保存的内容')
}
</script>

<style lang="scss" scoped>
.novel-content-editor {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

  .editor-header {
    padding: 16px;
    border-bottom: 1px solid #e4e7ed;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .header-left {
      h3 {
        margin: 0;
        font-size: 16px;
        color: #303133;
      }
    }

    .header-right {
      display: flex;
      gap: 8px;
    }
  }

  .editor-content {
    flex: 1;
    padding: 16px;
    overflow-y: auto;

    :deep(.el-textarea__inner) {
      height: 100%;
      font-size: 14px;
      line-height: 1.6;
      font-family: 'Microsoft YaHei', sans-serif;
    }
  }
}
</style> 